package cmu.mobile.lab;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class AddItem extends Activity {
	private static final int GET_CAMERA_CODE = 3;
	SharedPreferences prefs;
	private static final String GET_PICTURE_CODE = "previewPictureAdd";
	Bitmap picture;
	ImageView previewPicture;
	Uri uri;
	String picturePath;
	//Button next;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_additem); //to be added
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		final Bundle extras = getIntent().getExtras();

		
		previewPicture = ((ImageView)findViewById(R.id.PreviewImage));
		//next = ((Button)findViewById(R.id.NextButton));
		
		
		prefs = PreferenceManager.getDefaultSharedPreferences(AddItem.this);
		picturePath = prefs.getString(GET_PICTURE_CODE, picturePath);
		
		if (picturePath != null)
		{
			Uri u = Uri.parse("content://media" + picturePath);
			previewPicture.setImageURI(u);
//			next.setEnabled(true);
		}
//		else
//		{
//			next.setEnabled(false);
//		}
		
		// take photo button
		findViewById(R.id.CameraButton).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Call take photo
				Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(cameraIntent, GET_CAMERA_CODE);
			}
		});
		
		// back button
		findViewById(R.id.BackButton).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				picturePath = null;
        		SharedPreferences.Editor spe = prefs.edit();
        		//spe.clear();
        		spe.putString(GET_PICTURE_CODE, picturePath);
        		spe.commit();
				previewPicture.setImageResource(R.drawable.camera);
				finish();
			}
		});
		
		// next button
		findViewById(R.id.NextButton).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
        		//spe.clear();
        		picturePath = prefs.getString(GET_PICTURE_CODE, "NO IMAGE");
        		previewPicture.setImageResource(R.drawable.camera);
				Intent itemInfoIntent = new Intent(AddItem.this, ItemInfo.class);
				if (!picturePath.equals("NO IMAGE")) {
					itemInfoIntent.putExtra("imagePath", getRealPathFromURI(Uri
							.parse("content://media" + picturePath)));
				}
				else {
					itemInfoIntent.putExtra("imagePath", "");

				}
				itemInfoIntent.putExtra("ownerid", extras.getString("ownerid"));
//				Toast.makeText(AddItem.this, getRealPathFromURI(Uri
//						.parse("content://media" + picturePath)), 
//						Toast.LENGTH_LONG).show();
				startActivity(itemInfoIntent);
			}
		});
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (GET_CAMERA_CODE): {
			if (resultCode == Activity.RESULT_OK) {
				picture = (Bitmap) data.getExtras().get("data");
				((ImageView)findViewById(R.id.PreviewImage)).setImageBitmap(picture);
                ContentValues values = new ContentValues();
                	values.put(Images.Media.TITLE, "title");
                	values.put(Images.Media.BUCKET_ID, "test");
                	values.put(Images.Media.DESCRIPTION, "test Image taken");
                	values.put(Images.Media.MIME_TYPE, "image/jpeg");
                uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
                
                picturePath = uri.getPath();
                prefs = PreferenceManager.getDefaultSharedPreferences(AddItem.this);
        		SharedPreferences.Editor spe = prefs.edit();
        		spe.putString(GET_PICTURE_CODE, picturePath);
        		spe.commit();
                
        		OutputStream outputstream;
                try {
                        outputstream = getContentResolver().openOutputStream(uri);

                        picture.compress(Bitmap.CompressFormat.JPEG, 70, outputstream);
                        outputstream.close();
                } catch (FileNotFoundException e) {
                        //
                }catch (IOException e){
                        //
                }
                

//    			next.setEnabled(true);
			}
			break;

		}
		}
	}
	
	public String getRealPathFromURI(Uri contentUri) {

		// can post image
		String [] proj={MediaStore.Images.Media.DATA};
		Cursor cursor = managedQuery( contentUri,
				proj, // Which columns to return
				null,       // WHERE clause; which rows to return (all rows)
				null,       // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();

		return cursor.getString(column_index);
	}


}
